package com.rupyi.service.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.mbp.ServiceBaseEntity;
import com.ruoyi.common.core.web.domain.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * MP注入处理器
 *
 * @author Lion Li
 * @date 2021/4/25
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            // idos 插入
            if (ObjectUtil.isNotNull(metaObject) && (metaObject.getOriginalObject() instanceof ServiceBaseEntity)) {
                String userId = "1";
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
                this.setFieldValByName("createTime", new Date(), metaObject);
                this.setFieldValByName("creatorId", userId, metaObject);
                this.setFieldValByName("updateTime", new Date(), metaObject);
                this.setFieldValByName("updateUserId", userId, metaObject);
                this.setFieldValByName("deleteFlag", false, metaObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                String userId = "1";
                this.setFieldValByName("updateBy", userId, metaObject);
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    /**
     * 获取登录用户名
     */
    private String getLoginUsername() {
        return "admin";
    }

}
